package com.csh.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csh.order.entity.TbGoods;
import com.csh.order.entity.dto.GoodsEs;
import com.csh.order.entity.dto.LogGoodsAdmin;
import com.csh.order.mapper.TbGoodsMapper;
import com.csh.utils.ResultResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@EnableScheduling
public class OrderController {
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private static boolean cj=false;
    @Autowired
    TbGoodsMapper tbGoodsMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 创建索引映射
     *
     */
    @Scheduled(fixedDelay = 1000*2)
    public String EsIndexes(){
        if(cj){
            return null;
        }
        if(!elasticsearchRestTemplate.indexOps(TbGoods.class).exists()){
            elasticsearchRestTemplate.indexOps(TbGoods.class).create();
            Document mapping = elasticsearchRestTemplate.indexOps(TbGoods.class).createMapping();
            elasticsearchRestTemplate.indexOps(TbGoods.class).putMapping(mapping);
        }
        cj=true;
        return null;
    }
    @Scheduled(fixedDelay = 1000*5)
    public void incrementSynchronization(){
        Object keyTime = redisTemplate.opsForValue().get("key");
        if(keyTime==null){
            QueryWrapper<TbGoods> wrapper=new QueryWrapper<>();
            wrapper.lambda().orderByDesc(TbGoods::getCreatTime);
            List<TbGoods> goods = tbGoodsMapper.selectList(wrapper);
            //全量同步
            elasticsearchRestTemplate.save(goods);
            //倒叙排类 拿第一个对象的时间就能知道左后添加的数据的时间
            TbGoods tbGoods = goods.get(0);
            //把左后的时间保存到redis中,方便我们以后找新添加的数据(只需找到比这个时间大的数据就是我们新添加的）
            redisTemplate.opsForValue().set("key",tbGoods);
        }
        else{
            QueryWrapper<TbGoods> wrapper=new QueryWrapper<>();
            wrapper.lambda().orderByDesc(TbGoods::getCreatTime);
            wrapper.lambda().gt(TbGoods::getCreatTime,keyTime);
            List<TbGoods> goods = tbGoodsMapper.selectList(wrapper);
            if(goods!=null&&goods.size()>0){
                elasticsearchRestTemplate.save(goods);
                //倒叙排类 拿第一个对象的时间就能知道左后添加的数据的时间
                TbGoods tbGoods = goods.get(0);
                //把左后的时间保存到redis中,方便我们以后找新添加的数据(只需找到比这个时间大的数据就是我们新添加的）
                redisTemplate.opsForValue().set("key",tbGoods);
            }
        }
        return;
    }

    @PostMapping("/searchByWord")
    public Map searchByWord(@RequestBody GoodsEs goodsEs){
        //分页
        PageRequest pageRequest = PageRequest.of(goodsEs.getPageNum(), goodsEs.getPageSize());
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //把查询条件拼接起来
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //模糊查询
        if(goodsEs.getGoodsName()==null){
            boolQueryBuilder.must(
                    QueryBuilders.matchAllQuery()
            );
        }else{
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("goodsName",goodsEs.getGoodsName())
            );
        }
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>").postTags("</font>").field("goodsName");
        //倒叙排序
        FieldSortBuilder price = new FieldSortBuilder("price").order(SortOrder.DESC);
        builder.withPageable(pageRequest).withSort(price).withHighlightBuilder(highlightBuilder).withQuery(boolQueryBuilder);
        //通过条件查询出来数据
        SearchHits<TbGoods> search = elasticsearchRestTemplate.search(builder.build(), TbGoods.class);
        long token = elasticsearchRestTemplate.count(builder.build(), TbGoods.class);
        //把查询出来的数据转换成List<>类型
        List<SearchHit<TbGoods>> searchHits = search.getSearchHits();
        //循环添加数据
        List<TbGoods> list=new ArrayList<>();
        searchHits.forEach(item->{
            TbGoods tbGoods = item.getContent();
            List<String> goodsName = item.getHighlightField("goodsName");
            if(goodsName!=null&&goodsName.size()>0){
                String s = goodsName.get(0);
                tbGoods.setGoodsName(s);

            }
            list.add(tbGoods);
        });
        Map map=new HashMap();
        map.put("list",list);
        map.put("pageNum",goodsEs.getPageNum());
        map.put("pageSize",goodsEs.getPageSize());
        map.put("token",token);
        return map;

    }
//    @PostMapping("/findGoodsUpdate")
//    public ResultResponse findGoodsUpdate(@RequestBody LogGoodsAdmin logGoodsAdmin){
//
//    }


}
